package com.hsy.linemoney.beans;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Locale;

/**
 * Created by MartinKent on 2016/9/8.
 */
public class LocalPair {
    public String name;
    public Locale locale;

    public LocalPair() {
    }

    public LocalPair(String name, Locale locale) {
        this.name = name;
        this.locale = locale;
    }

    @Override
    public String toString() {
        return "{\"LocalPair_name\":\"" + name + "\",\"LocalPair_lang\":\"" + locale.getLanguage() + "\"}";
    }

    public static <T extends LocalPair> T fromString(String src, Class<T> cls) {
        try {
            JSONObject object = new JSONObject(src);
            if (object.has("LocalPair_name") && object.has("LocalPair_lang")) {
                try {
                    T p = cls.newInstance();
                    p.name = object.getString("LocalPair_name");
                    p.locale = new Locale(object.getString("LocalPair_lang"));
                    return p;
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e(cls.getSimpleName().substring(0, Math.min(20, cls.getSimpleName().length())), "src invalid.");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e(cls.getSimpleName().substring(0, Math.min(20, cls.getSimpleName().length())), e.getMessage());
        }
        return null;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof LocalPair)) return false;
        LocalPair localPair = (LocalPair) o;
        return !(name != null ? !name.equals(localPair.name) : localPair.name != null);
    }

    @Override
    public int hashCode() {
        return name != null ? name.hashCode() : 0;
    }
}
